<?php

require_once(APP.'libs'.DS.'system_properties.php');
App::import('Vendor','/infolex/app_config');
class Count extends AppModel
{
	var $name='User';
	var $validate = array();

	function connect(){
	    $GLOBALS['dbs'] = array(
	    'renren' => new mysqli('localhost','tryapp', 'tryapp_654321' ,'tryapp'),
	    'yoka' => new mysqli('localhost','tryapp', 'tryapp_654321' ,'tryapp_y'),
	    'myspace' => new mysqli('localhost','tryapp', 'tryapp_654321' ,'tryapp_m'),
	    'sina' => new mysqli('localhost','tryapp', 'tryapp_654321' ,'tryapp_s'),
	    );
	    foreach ($GLOBALS['dbs'] as $name=>$db){
	       $db->query("set names 'utf8'");
	    }

	}
	function getDatas($db, $sql){
	    $rows = array();
	    $res = $db->query($sql);
	    if (empty($res)){
	        return array();
	    }
	    while ($r = $res->fetch_assoc()){
	        $rows[] = $r;
	    }
	    return $rows;
	}
	function getDataNumber($db, $sql, $col){
	    $rows = array();
	    $res = $db->query($sql);
	    if (empty($res)){
	        return 0;
	    }
	    $r = $res->fetch_assoc();
	    if (!empty($r[$col])){
	        return $r[$col];
	    } else {
	       return 0;
	    }
	}
	function searchAndCount($q) {
   	    $time_start = empty($_REQUEST['from'])?0:trim($_REQUEST['from']);
		$time_end = empty($_REQUEST['end'])?0:trim($_REQUEST['end']);
	    $start_time = date('Y-m-d',strtotime($time_start));
	    $end_time = date('Y-m-d',strtotime($time_end.' +1day'));
	    $dbs = $GLOBALS['dbs'];
	    $rets = array();
	    foreach ($dbs as $name=>$db){
	        $data = array();
	        $sql = "SELECT * FROM `g_products` WHERE `g_name` LIKE '%{$q}%' and g_price=0 order by in_list desc";
	        $pids = $this->getDatas($db,$sql);
	        foreach ($pids as $p) {
	            $pid = $p['g_id'];
	            $data[$pid]['info'] = $p;
	            $sql = "SELECT count(1) as c FROM `g_clicklogs` use index(ix) WHERE product_id={$pid} and time>='{$start_time}' and time <= '{$end_time}'";
	            $data[$pid]['click'] = $this->getDataNumber($db,$sql,'c');
	            $sql = "SELECT count(1) as c FROM `g_viewlogs` use index(ix)  WHERE product_id={$pid} and time>='{$start_time}' and time <= '{$end_time}'";
	            $data[$pid]['view'] = $this->getDataNumber($db,$sql,'c');
	        }
	        $rets[$name] = $data;
	    }
	    return $rets;
	}
	
}